<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" scanType="1" :leftType="'1'"  @clickLeftBack="clickLeftBack" :title="$t('distributedOut.pageTitle')" rightText="扫描记录"
				@clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<scroll-view class="scroll-view_H" scroll-y>
				
			<!-- <view class="page-auto" :style="'height: calc(100vh - '+ navHeight +'px);'"> -->
				<!-- 调拨单信息 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{$t('distributedOut.informationOut')}}
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{$t('smashRemoval.letterOfAdvice')}}：</text>
						<text>{{data.warehouseInfo.dnCode}}</text>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{$t('pageTranslation.deliveryDate')}}：</text>
						<text>{{data.warehouseInfo.dnDate}}</text>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{$t('smashRemoval.deliveredTotal')}}：</text>
						<text>{{data.warehouseInfo.sumQty}}</text>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{$t('distributedEnter.quantityOutStorage')}}：</text>
						<text>{{data.warehouseInfo.sumScan}}</text>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title"><text class="required-color">*</text>{{$t('distributedOut.organizationOut')}}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.organizationOutList"
							:placeholder="$t('stockManage.placeholder')" :isJSON="true" keyName="text" v-model="data.selectedOut"
							@select="selectOut"></superweiCombox>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title"><text class="required-color">*</text>{{$t('distributedOut.organizationIn')}}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.organizationEnterList"
						:placeholder="$t('stockManage.placeholder')" :isJSON="true" keyName="text" v-model="data.selectedEnter"
							@select="selectEnter"></superweiCombox>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{$t('distributedEnter.materialCoded')}}</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barcode" type="search" :disabled="data.warehouseInfo.sumQty == data.warehouseInfo.sumScan"
							 :placeholder="$t('distributedOut.pleaseMaterial')" @confirm="confirm('barcode')" @iconClick="iconClick($event,'barcode')">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{$t('distributedOut.palletBarcode')}}</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.trayCode" type="search" :disabled="data.barcode == ''"
							:placeholder="$t('distributedOut.pleasePallet')" @confirm="confirm('tray')" @iconClick="iconClick($event,'tray')">
						</uni-easyinput>
					</view>
				</view>
				<!-- 当前扫描条码 -->
				<view class="custom-form-card">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{$t('distributedOut.atPresent')}}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialCoded')}}：</text>{{data.currentBarcode.barcode}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{data.currentBarcode.materialSpec}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{data.currentBarcode.materialCode}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{data.currentBarcode.materialName}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('translationImage.traySize')}}：</text>{{data.currentBarcode.qrCode}}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{data.currentBarcode.currentQty}}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.uom')}}：</text>{{data.currentBarcode.unit}}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedOut.warehouse')}}：</text>{{data.currentBarcode.warehouseCode}}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedOut.location')}}：</text>{{data.currentBarcode.locationCode}}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{$t('materials.deliveryInformation')}}</text>
					<view class="gui-title-line"></view>
				</view>
				<uni-card class="element-auto gui-margin-top card-my">
					<view class="element-auto" style="height: 500rpx">
						<zb-table :columns="data.column" :stripe="true" :border="true"
							:data="tableData.list" @customLook="customBtnFn" :cell-style="cellStyle"
							:cell-header-style="cellHeaderStyle">
						</zb-table>
					</view>
				</uni-card>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box" @click="submit">
					<view class="page-bottomBtn bottomBtn-bgcolor-green">
						{{$t('calendar.submit')}}
					</view>
				</view>
			<!-- </view> -->
		</scroll-view>
			<gui-top-message ref="guitopmsg">
				<view class="gui-bg-red">
					<text style="line-height:88rpx; font-size:26rpx; text-align:center;"
						class="gui-block-text gui-color-white gui-icons">&#xe646; {{$t('smashRemoval.codesRepeatedly')}}</text>
				</view>
			</gui-top-message>
			<!-- 普通弹窗 -->
			<uni-popup ref="popupDetail" type="center">
				<view class="input-dialog-box"
					style="padding: 40rpx 20rpx 20rpx 20rpx;border-radius: 22rpx;width: 600rpx;">
					<uni-icons class="popup-close-icons" type="closeempty" color="#9C9C9C" size="26"
						@click="closePopup"></uni-icons>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text> {{data.popupData.materialCode}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text> {{data.popupData.materialName}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text> {{data.popupData.spec}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('translationImage.totalDocuments')}}：</text> {{data.popupData.saleQty}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.quantityOutStorage')}}：</text> {{data.popupData.scanQty}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.scannedQuantity')}}：</text> {{data.popupData.currentscanQty}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{$t('distributedEnter.uom')}}：</text> {{data.popupData.saleUnit}}
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		toRaw,
		watchEffect,
		computed,
		watch
	} from 'vue'
	import {
		navigate
	} from '@/utils/routerSkip.js';
	import {
		scanDistributedTransferOutBarcode,
		findK3WmsDnHById,
		checkQrCodeIsBindWMS,
		submitDistributedTransferOut
	} from '@/api/api.js'
	import pdaScan from '@/hooks/pdaScan.js'
	import {
		getDataDictionaryFn,
		pitchOnFn,
		sortClassMaterialcode
	} from '@/utils/index.js'
	import superweiCombox from '@/components/superweiCombox';
	import tableColor from '@/hooks/tableColor.js';
	import graceJS from "@/Grace6/js/grace.js";
	import { basPdaOperationLogFn } from '@/utils/index.js';
	import { OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN, OPERATION_CHECK} from '@/constant/index.js'
	import {
		useStore
	} from "vuex";
	import { onBackPress } from '@dcloudio/uni-app';
	//JS国际化引入
	import { useI18n } from 'vue-i18n';
	components: {
		superweiCombox
	}
	const { t } = useI18n();

	const { scan } = pdaScan()
	let {
		tableData
	} = tableColor();
	const {
		cellStyle,
		cellHeaderStyle
	} = tableColor();
	let guitopmsg = ref(null)
	let popupDetail = ref(null)
	const props = defineProps({id:String})
	let store = useStore();
	let data = reactive({
		value: ['1'],
		inputType:'barcode',
		popupData:{},
		scanNum:0,
		warehouseInfo:{},
		warehouseList: [],
		organizationEnterList: [],
		organizationOutList: [],
		selectedOut: '',
		selectedEnter: '',
		outId: '',
		EnterId: '',
		warehouse: '',
		barcode: '',
		trayCode: '',
		currentBarcode:{},
		column: [{
				name: 'age',
				type: 'ailibtn',
				label:t('translationImage.operation'),
				scanValue: '',
				fixed: true,
				width: 80,
			},
			{
				name: 'materialCode',
				label: t('distributedEnter.materialCode'),
				fixed: true,
				width: 100,
				emptyString: '--'
			},
			{
				name: 'materialName',
				label: t('distributedEnter.materialName'),
				width: 120,
			},
			{
				name: 'spec',
				label: t('distributedEnter.materialSpec'),
				width: 240,
			},
			{
				name: 'saleUnit',
				label: t('distributedEnter.uom'),
				width: 60,
			},
			{
				name: 'saleQty',
				label: t('translationImage.totalDocuments'),
				width: 90,
			},
			{
				name:'scanQty',
				label: t('distributedEnter.quantityOutStorage'),
				width: 120,

			},
			{
				name: 'currentscanQty',
				label: t('distributedEnter.scannedQuantity'),
				width: 120,
			}
		]
	})
	data.scanList = computed(() => {
		return store.state.k3distributedOutData
	})
	const navHeight = computed(()=>{
		return store.state.navHeight
	})
	watch(()=>data.scanList, (newVal, oldVal) => {
		console.log('newVal, oldVal', newVal, oldVal)
		console.log(data.scanList)
		let tepData = toRaw(newVal)
		let list = sortClassMaterialcode(tepData)
		console.log(list,'listlistlistlist')
		if(list.length){
			let tepList = []
			list.forEach(x => {
				let item = {
					child:x,
					currentqty:0
				}
				x.forEach(k=>{
					item.materialcode = k.materialcode
					item.materialname = k.materialname
					item.spec = k.spec
					item.unit = k.unit
					item.housecode = k.housecode
					item.currentqty += Number(k.currentqty)
				})
				tepList.push(item)
			});
			console.log(tepList,'tepList')
			tableData.list.forEach(x=>{
				tepList.forEach(k=>{
					if(k.materialcode == x.materialCode){
						x.currentscanQty = k.currentqty
					}
				})
			})
			tableData.list.map((item,index) => {
			   if(item.materialCode ==  data.currentBarcode.materialcode){
			      tableData.list.unshift(tableData.list.splice(index , 1)[0]);
			   }
			})
		}else{
			tableData.list.forEach(x=>{
				x.currentscanQty = 0
			})
		}
	}, {
		immediate: true,
		deep: true
	});
	onMounted(() => {
		console.log('开始监听PDA扫码')
		uni.$on('scancodedate', (res) => {
			console.log('获取到的code：' + res.code)
			console.log(data.inputType,'data.inputType');
			console.log(data.inputType === 'barcode','data.inputType === barcode');
			if(data.warehouseInfo.sumQty == data.warehouseInfo.sumScan) return
			if(data.inputType === 'barcode'){
				
				console.log('barcode');
				data.barcode = res.code
				getCode(res.code, 'pda')
			}else{
				if(res.code.length>9)
				{
					uni.showToast({
						title:t('Common.scanerror'),
						icon:'none'
					})
					return
				}
				data.trayCode = res.code
				checkQrCodeIsBindWMSFn(res.code, 'pda')
			}
			
		})
		getInitData()
		findWmsDnHByIdFn()
	})
	onBackPress((options) => {
		if (options.from == 'backbutton') {
			navBackCheck()
			return true;
		}
	})
	//导航栏左侧返回
	const clickLeftBack = () => {
		navBackCheck()
	}
	const navBackCheck = () =>{
		if(!data.scanList.length){
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					store.commit('removeK3DistributedOutData')
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	// 检查木托盘有没有被绑定
	const checkQrCodeIsBindWMSFn = (code) => {
		// 判断物料条码有没有去搜索
		if(data.scanNum == 0){
			uni.showToast({
				title: t('JsInternational.searchMatterial'),
				icon: 'none'
			})
			return
		}
		// 判断这个托盘本次有没有绑定过
		let isBind = data.scanList.some(x=>x.qrCode == code);
		if(isBind) {
			uni.showToast({
				title: t('JsInternational.trayBlinded'),
				icon: 'none'
			})
			return
		}
		let parmes = {
			qrCode:data.trayCode
		}
		checkQrCodeIsBindWMS(parmes).then(res=>{
			try {
				let inputParameter = JSON.stringify(parmes)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '上基材分布式调出'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode:res.status,//返回状态
					errorMessage:res.message,//错误信息
					isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType:OPERATION_CHECK
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			if (res.status == 200) {
				data.currentBarcode.qrCode = data.trayCode;
				store.commit('addk3DistributedOutData', data.currentBarcode);
				console.log(1111,data.currentBarcode)
				data.barcode = ''
				data.trayCode = ''
				uni.showToast({
					title:t('JsInternational.blind'),
					icon: 'none'
				})
				data.inputType = 'barcode'
				data.scanNum = 0
			} else {
				uni.showToast({
					title: res.message,
					icon: 'none'
				})
			}
			console.log(res,'检查木托盘有没有被绑定')
		})
	}
	// 获取code
	const getCode = (code,type) => {
		console.log(`拿到code,code为${code},type类型为${type}`)
		// 判断这个托盘本次有没有绑定过
		console.log(data.scanList,'data.scanList')
		let isBind = data.scanList.some(x=>x.barcode == code);
		if(isBind) {
			uni.showToast({
				title: t('JsInternational.scanned'),
				icon: 'none'
			})
			return
		}
		let parmes = {
			barcode: code,
			selectType: 'UpperBasMaterial',
			barcodestatus: '1',
			dnHId:props.id,
			client:'AF'
		}
		scanDistributedTransferOutBarcode(parmes).then(res => {
			try {
				let inputParameter = JSON.stringify(parmes)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '上基材分布式调出'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode:res.code,//返回状态
					errorMessage:res.message,//错误信息
					isPass:res.code == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType:OPERATION_SCAN
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			console.log(res)
			if (res.code == 200) {
				// 判断该条码对应的单据还剩多少数量
				let tep = tableData.list.filter(x=>x.materialCode == res.result.materialCode);
				let bool = tableData.list.some((item) => {
					return item.materialCode == res.result.materialCode
				})
				if(!bool){
					uni.showToast({ title:t('materials.materialIsNot'), icon: "none" });
					return
				}
				if(tep.length){
					// 筛选出和当前扫码一直的物料并提位
					if (tableData.list.length && tableData.list.length != 1) {
						for (var i = 0; i < tableData.list.length; i++) {
							var item = {}
							if (tableData.list[i].materialCode === res.result.materialCode) {
								item = tableData.list[i]
								tableData.list.splice(i, 1);
								tableData.list.unshift(item)
								break;
							}
						}
					}
				    let num = Number(tep[0].saleQty) -  Number(tep[0].scanQty) - tep[0].currentscanQty;
					console.log(num,'还剩多少')
					if(num < 0) return 	uni.showToast({title: t('JsInternational.deliveryMaterial'),icon: 'none',duration:1500})
					let subNum = num - res.result.currentQty;
					if(subNum < 0) return 	uni.showToast({title:t('materials.scannedBarcodes')+`${tep[0].materialName}`+t('hardware.receiptsQty'),icon: 'none',duration:2000})
				}
				data.scanNum ++
				if(data.scanNum > 1){
					guitopmsg.value.open();
					return;
				}
				data.currentBarcode = res.result
				data.value = ['0']
				data.inputType = 'tray' 
			} else {
				uni.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		})
	}
	// 获得焦点
	const getFocus = (type) => {
		console.log(type)
		data.inputType = type;
	}
	// 用户调起相机扫码
	const iconClick = async (type,inputType) => {
		console.log(type)
		data.inputType = inputType;
		if(type === 'suffix'){
		   let code = await scan()
		   if(inputType === 'barcode'){
			   data.barcode = code
			   getCode(code,'scan')
		   }else{
			   if(code.length>9)
			   {
			   	uni.showToast({
			   		title:t('Common.scanerror'),
					icon:'none'
			   	})
			   	return
			   }
			   checkQrCodeIsBindWMSFn(code, 'scan')
		   }
		}
	}
	// 用户点击键盘上搜索
	const confirm = (type) => {
		data.inputType = type;
		let code = type == 'barcode' ? data.barcode : data.trayCode
		if(data.inputType === 'barcode'){
			getCode(code,'keydown')
		}else{
			if(code.length>9)
			{
				uni.showToast({
					title:t('Common.scanerror'),
					icon:'none'
				})
				return
			}
			checkQrCodeIsBindWMSFn(code, 'keydown')
		}
		
	}
	// 获取调出单详情
	const findWmsDnHByIdFn = () => {
		let parmes = {
			id:props.id,
			client:"AF"
		}
		findK3WmsDnHById(parmes).then(res=>{
			try {
				let inputParameter = JSON.stringify(parmes)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '上基材分布式调出'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode:res.code,//返回状态
					errorMessage:res.message,//错误信息
					isPass:res.code == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType:OPERATION_LOOK
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			console.log(res,'findWmsDnHById');
			if (res.code == 200) {
				data.warehouseInfo = res.result;
				let tep = res.result.wmsDnDs
				tableData.list = tep.map(x=>{
					x.currentscanQty = 0 
					return x
				});
			} else {
				uni.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		})
	}
	const selectEnter = (e) => {
		console.log(e.value)
		this.EnterId = e.value
	}
	const selectOut = (e) => {
		console.log(e.value)
		this.outId = e.value
	}
	const submit = () => {
		if(!data.scanList.length){
			uni.showToast({
				title: t('pageTranslation.plsScanThe'),
				icon: 'none'
			})
			return
		}
		let list = data.scanList.map(x=>{
			x.materialCode = x.materialCode
			x.currentQty = x.currentQty
			return x
		})
		// let parmes = {
		// 	dnHId:props.id,
		// 	barcodes:list,
		// 	dnTypeCode:'sjc',
		// 	sourceBillCode: data.warehouseInfo.dnCode,
		// 	client:'AF'
		// }
		
		let parmes = {
				dnHId: props.id,
				barcodes: list,
				lstBarcodeItem: list,
				dnTypeCode: 'sjc',
				sourceBillCode: data.warehouseInfo.dnCode,
				outOrg: data.selectedOut,
				inOrg: data.selectedEnter,
				client:'AF'
			}

		// 添加加载框
		uni.showLoading({
			title: 'loading',
			mask: true
		});
		submitDistributedTransferOut(parmes).then(res=>{
			try {
				let inputParameter = JSON.stringify(parmes)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '上基材分布式调出'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode:res.code,//返回状态
					errorMessage:res.message,//错误信息
					isPass:res.code == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType:OPERATION_COMMIT
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			if (res.code == 200) {
				//隐藏加载框
				uni.hideLoading();
				uni.showToast({
					title: t('smashRemoval.submitSuccessfully'),
					icon: 'none',
					duration:2000,
					complete: () => {
						store.commit('removeK3DistributedOutData')
						setTimeout(function () {
							uni.navigateBack()
						}, 1000);
						// uni.navigateBack()
					}
				})
			} else {
				uni.showToast({
					title: res.message,
					icon: "none"
				});
			}
		})
		
	}
	const getInitData = async () => {
		// 获取调入组织信息
		data.organizationOutList = await getDataDictionaryFn('TransferOutOrganization') 
		let tepSelect1 = pitchOnFn(data.organizationOutList)
		data.selectedOut = tepSelect1[0].text
		data.outId = tepSelect1[0].value

		// 获取调出组织信息
		data.organizationEnterList = await getDataDictionaryFn('OrganizationalInformation')
		let tepSelect2 = pitchOnFn(data.organizationEnterList)
		data.selectedEnter = tepSelect2[0].text
		data.EnterId = tepSelect2[0].value
	}
	const clickRight = () => {
		navigate({
			url: '/pages/distributed/eletileOutIndexRecord'
		})
	}
	const customBtnFn = (item, index) => {
		console.log(item, index)
		data.popupData = item;
		popupDetail.value.open()
	}
	const closePopup = () => {
		popupDetail.value.close()
	}
	const rowClick = (row,index) => {
		console.log(111);
		console.log(row,index);
	}
</script>

<style scoped lang="scss">
.scroll-view_H{
	position: fixed;
	top: 48px;
	bottom: 100rpx;
	left: 0px;
	width: 100%;
}
.page-bottom-box{
	position: fixed;
	left: 0px;
	bottom: 0px;
	z-index: 2;
	width: 100%;
}
</style>
